/**
 * Project: apollo-base-dal
 * 
 * File Created at 2017年2月15日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.dal.conf;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySources;

/** 
* @ClassName: PropertyFileUtils 
* @Description: 解析properties文件工具
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2017年2月15日 下午3:03:06 
* @version V1.0 
*/
public class PropertyFileUtils {

	public static Map<String, Object> getSubProperties(PropertySources propertySources, String keyPrefix) {
		return PropertyFileUtils.getSubProperties(propertySources, null, keyPrefix);
	}

	public static Map<String, Object> getSubProperties(PropertySources propertySources, String rootPrefix, String keyPrefix) {
		RelaxedNames keyPrefixes = new RelaxedNames(keyPrefix);
		Map<String, Object> subProperties = new LinkedHashMap<String, Object>();
		for (PropertySource<?> source : propertySources) {
			if (source instanceof EnumerablePropertySource) {
				for (String name : ((EnumerablePropertySource<?>) source).getPropertyNames()) {
					String key = PropertyFileUtils.getSubKey(name, rootPrefix, keyPrefixes);
					if (key != null && !subProperties.containsKey(key)) {
						subProperties.put(key, source.getProperty(name));
					}
				}
			}
		}
		return Collections.unmodifiableMap(subProperties);
	}

	private static String getSubKey(String name, String rootPrefixes, RelaxedNames keyPrefix) {
		rootPrefixes = (rootPrefixes == null ? "" : rootPrefixes);
		for (String rootPrefix : new RelaxedNames(rootPrefixes)) {
			for (String candidateKeyPrefix : keyPrefix) {
				if (name.startsWith(rootPrefix + candidateKeyPrefix)) {
					return name.substring((rootPrefix + candidateKeyPrefix).length());
				}
			}
		}
		return null;
	}
}
